<?php
/**
 * 如果mike的合同到时间了处理，直接过滤
 * TODO 为了更快增加临时表,存取已经发送过的人
 */
apf_require_class('Oa_Job_Abstract');
apf_require_class('Bll_Flow_OperateLog');
apf_require_class('Const_Flow');
apf_require_class('Bll_Flow_Info');
apf_require_class('Bll_Flow_ApplyRelation');
apf_require_class('Bll_Flow_UserRegular');
apf_require_class('Bll_Flow_UserRenew');
class Oa_Job_Flow_CheckRegularRenew extends Oa_Job_Abstract {

    private $writedb = "hroa_master";//写数据库
    private $_error_info = array();//异常数据

    public function run($params){
        $time_start = time();
        $this->log("START".date('Ymd')."==开始执行啦！");//方便搜索时找到指定的位置

        $this->hr_bll = new Bll_Hr_OutInterface();
        $this->field = $this->_get_user_field();

        $this->log_bll = new Bll_Flow_OperateLog();
        $this->flow_bll = new Bll_Flow_Info();
        $this->rel_bll = new Bll_Flow_ApplyRelation();
        $this->regular_bll = new Bll_Flow_UserRegular();
        $this->renew_bll = new Bll_Flow_UserRenew();

        $type = empty($params['type']) ? 'today' : $params['type'];
        $day = empty($params['day']) ? 0 : $params['day'];
        if($type == 'today'){
            $this->_today = strtotime(date('Ymd'));
            if($day){
                $this->_today = strtotime($day);
            }
        }elseif($type == 'init'){
            $this->_today =strtotime(date('Ymd'));//这是是第一次初始化时使用
            $time = $this->_today+30*86400;
            $this->_t_time = date('Ymd',$time);
            $all_user = $this->_get_all_users();

            if(!empty($all_user['regular_list'])){
                $this->_build_regular_users($all_user['regular_list']);
                $this->log('30天需转正员工信息 End');
            }
            if(!empty($all_user['renew_list'])){
                $this->_build_renew_users($all_user['renew_list']);
                $this->log('30天需续签员工信息 End');
            }
            $this->log("这是是第一次初始化时使用");exit;
        }elseif($type == 'regular'){
            $this->_today = strtotime($day);
            $this->_get_yeaterday_regular();
            $this->log('昨天需转正员工信息 End');exit;
        }

        $_time = $this->_today+30*86400;//合同结束时间等于这个
        $this->_time = date('Ymd',$_time);//30天之后的时间,需要提前一天

        $this->_get_yeaterday_regular();
        $this->log('昨天需转正员工信息 End');

        //$this->_get_yeaterday_renew();
        //$this->log('昨天需续签员工信息 End');

        $all_user['regular_list'] = $this->_get_regular_users();
        $all_user['renew_list'] = $this->_get_renew_users();
        //30天内需要提示的人
        if(!empty($all_user['regular_list'])){
            $this->_build_regular_users($all_user['regular_list']);
            $this->log('30天需转正员工信息 End');
        }
        if(!empty($all_user['renew_list'])){
            $this->_build_renew_users($all_user['renew_list']);
            $this->log('30天需续签员工信息 End');
        }
        //如果有异常数据，给开发人员发邮件
        if(!empty($this->_error_info)){
            apf_require_class('Tools_SendMail');
            $content = implode("\n", $this->_error_info);
            Tools_SendMail::get_instance()->send('andycao@anjuke.com','员工转正续签==='.date('Y-m-d H:i',$this->_today),$content);
        }
        $this->log('(End Job--'.date('Y-m-d H:i:s').')'.($time_end-$time_start).'seconds');
    }

    private function _get_user_field(){
        $field = "user_id,user_code,user_name,office_mail,user_type,job_status,";
        $field .= "enter_date,indue_date,join_start,join_end,join_keep,work_city_id,";
        $field .= "trial_start,trial_end,trial_keep";
        return $field;
    }

    //30天内需要提示的人
    private function _get_regular_users(){
        $sql = "SELECT {$this->field} FROM user WHERE job_status=1 AND user_type=1 AND indue_date=".$this->_time;
        $tmp = $this->get_db_rows_assoc($sql,$this->writedb,array());
        if(empty($tmp)){
            return array();
        }
        return $tmp;
    }

    private function _get_renew_users(){
        $sql = "SELECT {$this->field} FROM user WHERE job_status=1 AND join_end=".$this->_time;
        $tmp = $this->get_db_rows_assoc($sql,$this->writedb,array());
        if(empty($tmp)){
            return array();
        }
        return $tmp;
    }
    //昨天应该转正而没有转的人
    private function _get_yeaterday_regular(){
        $in_date = $this->_today-86400;
        $in_date = date('Ymd',$in_date);
        $sql = "SELECT {$this->field} FROM user WHERE job_status=1 AND user_type=1 AND indue_date=".$in_date;
        $user_data = $this->get_db_rows_assoc($sql,$this->writedb,array());
        if(!empty($user_data)){
            $uids = array_keys($user_data);//应该转正的，但是流程还没有批完
            $sql_r = "SELECT * FROM user_regular WHERE user_id IN (".implode(',',$uids).")";
            $tmp = $this->get_db_rows_assoc($sql_r,$this->writedb,array());
            if(!empty($tmp)){//
                foreach($tmp as $val){
                    $this->log("[Indue]=====".$val['effect_date']."===".$val['user_id']."===".$val['flow_id']);
                    //无论领导同不同意都转正
                    $up_A = "UPDATE user SET user_type =  '2' WHERE  user_id =".$val['user_id'];
                    $this->execute( $up_A,array(), $this->writedb);

                    $up_B="UPDATE user_regular SET  apply_status =  '2' WHERE flow_id =".$val['flow_id'];
                    $this->execute( $up_B,array(), $this->writedb);

                    $up_C = "UPDATE apply_relation SET is_deleted =  '2' WHERE flow_id =".$val['flow_id'];
                    $this->execute( $up_C,array(), $this->writedb);

                    $flow_status=2;
                    if(empty($val['super_opinion'])){//说明领导没有操作过 write log
                        $flow_status = 4;
                        //写入operator_log表，标记为系统处理
                        $log_data = array(
                                'user_id'      => $val['user_id'],
                                'user_name'    => $val['user_name'],
                                'opt_user_id'  => $val['opt_user_id'],//system
                                'role_type'    => Const_Flow::ROLE_SUPERIOR,//领导同意
                                'work_city_id' => $user_data[$val['user_id']]['work_city_id'],
                                'flow_id'      => $val['flow_id'],
                                'flow_opt'     => Const_Flow::PHASE_41,
                                'flow_stage'   => Const_Flow::FLOW_REGULAR_2,
                                'flow_type'    => Const_Flow::FLOW_TYPE_REGULAR,
                                'effect_date'  => $val['effect_date'],
                        );
                        $this->log_bll->save_log($log_data);
                    }
                    $up_flow="UPDATE flow SET now_status =  '{$flow_status}',flow_stage=".Const_Flow::FLOW_REGULAR_2.",flow_opt=".Const_Flow::PHASE_41." WHERE flow_id =".$val['flow_id'];
                    $this->execute( $up_flow,array(), $this->writedb);
                }
            }
        }
        return true;
    }
    //得到昨天需要续签的
    private function _get_yeaterday_renew(){
        $in_date = $this->_today-86400;
        $in_date = date('Ymd',$in_date);
        $sql = "SELECT {$this->field} FROM user WHERE job_status=1 AND join_end=".$in_date;
        $user_data = $this->get_db_rows_assoc($sql,$this->writedb,array());
        if(!empty($user_data)){
            $uids = array_keys($user_data);//应该续签的，但是流程还没有批完
            $sql_r = "SELECT * FROM user_renew WHERE user_id IN (".implode(',',$uids).")";
            $tmp = $this->get_db_rows_assoc($sql_r,$this->writedb,array());
            if(!empty($tmp)){//
                foreach($tmp as $val){
                    $this->log("[JoinEnd]=====".$val['effect_date']."===".$val['user_id']."===".$val['flow_id']);
                    $up_B="UPDATE user_renew SET  apply_status =  '2' WHERE flow_id =".$val['flow_id'];
                    $this->execute( $up_B,array(), $this->writedb);
                    $up_C = "UPDATE apply_relation SET is_deleted =  '2' WHERE flow_id =".$val['flow_id'];
                    $this->execute( $up_C,array(), $this->writedb);

                    $flow_status=2;
                    if(!$val['super_opinion']){//说明领导没有操作过 write log
                        $flow_status = 4;
                        //写入operator_log表，标记为系统处理
                        $log_data = array(
                                'user_id'      => $val['user_id'],
                                'user_name'    => $val['user_name'],
                                'opt_user_id'  => $val['opt_user_id'],//system
                                'role_type'    => Const_Flow::ROLE_SUPERIOR,//领导同意
                                'work_city_id' => $user_data[$val['user_id']]['work_city_id'],
                                'flow_id'      => $val['flow_id'],
                                'flow_opt'     => Const_Flow::PHASE_61,
                                'flow_stage'   => Const_Flow::FLOW_RENEW_2,
                                'flow_type'    => Const_Flow::FLOW_TYPE_RENEW,
                                'effect_date'  => $val['effect_date'],
                        );
                        $this->log_bll->save_log($log_data);
                    }
                    $up_flow="UPDATE flow SET now_status =  '{$flow_status}',flow_stage=".Const_Flow::FLOW_RENEW_2.",flow_opt=".Const_Flow::PHASE_61." WHERE flow_id =".$val['flow_id'];
                    $this->execute($up_flow,array(), $this->writedb);
                }
            }
        }
        return $tmp;
    }
    //获取所有的在职员工
    private function _get_all_users(){
        $start = 0;
        $limit = 100;
        $result = array();
        while(true) {
            $sql = "SELECT {$this->field} FROM user WHERE job_status =1 AND user_id > {$start} ORDER BY user_id asc limit {$limit}";
            $tmp = $this->get_db_rows($sql,$this->writedb,array());
            if(empty($tmp)) {
                $this->log("取完所有用户数据!");
                break;
            }
            $count = count($tmp);
            $start = $tmp[$count - 1]['user_id'];
            $result = array_merge($result,$tmp);
        }
        $res = array();
        foreach($result as $val){
            if(empty($val['indue_date'])){
                $this->_error_info[]=$val['user_id']." Not Found indue_date";
                continue;
            }
            if(empty($val['join_end'])){
                $this->_error_info[]=$val['user_id']." Not Found join_end";
                continue;
            }
            if($val['user_type']==1 && $val['indue_date'] >= date('Ymd') && $val['indue_date']<= $this->_t_time){//试用员工
                $res['regular_list'][$val['user_id']] = $val;
            }
            if($val['join_end']<= $this->_t_time && $val['join_end'] >= date('Ymd') ){//可能需要续签的人
                $res['renew_list'][$val['user_id']] = $val;
            }
        }
        unset($result);
        return $res;
    }
    //找出正在试用的员工,提前30天发通知
    private function _build_regular_users($data){
        //取用户的职位信息
        $uids = array_keys($data);
        $jobinfo = $this->hr_bll->get_user_by_ids($uids);
        $sql = "SELECT * FROM user_regular WHERE user_id IN(".implode(',',$uids).") AND apply_status=1 ";
        $tmp_user_data = $this->get_db_rows_assoc($sql,$this->writedb,array());
        $has_user_data = array();
        if(!empty($tmp_user_data)){
            foreach($tmp_user_data as $val){
                $has_user_data[$val['user_id']] = $val;
            }
        }
        foreach($data as $val){
            if(!empty($has_user_data[$val['user_id']])){//事项中已存在的
                continue;
            }
            $super_data = $this->_get_user_super($val['user_id']);
            if(empty($super_data)){
                continue;
            }
            $in_flow = array(
                    'user_id'        => $val['user_id'],
                    'user_name'      => $val['user_name'],
                    'flow_type'      => Const_Flow::FLOW_TYPE_REGULAR,
                    'flow_stage'     => Const_Flow::FLOW_REGULAR_1,//当前阶段
                    'flow_opt'       => Const_Flow::PHASE_40,
                    'flow_role_list' => Const_Flow::ROLE_SUPERIOR,
                    'work_city_id'   => $val['work_city_id'],
                    'effect_date'    => $val['indue_date'],
                    'now_status'     => 1,
            );
            $flow_id = $this->flow_bll->insert_flow($in_flow);
            $this->log("[IndueSEND]=====".$val['indue_date']."===".$val['user_id'].$val['user_name'].$val['user_code']."===".$flow_id);
            //信息表
            $regular_data = array(
                    'flow_id'        => $flow_id,
                    'user_id'        => $val['user_id'],
                    'user_name'      => $val['user_name'].'-'.$val['user_code'],
                    'department_name'=> $jobinfo[$val['user_id']]['department_name'],
                    'job_name'       => $jobinfo[$val['user_id']]['job_name'],
                    'job_id'         => $jobinfo[$val['user_id']]['job_id'],
                    'work_city_id'   => $val['work_city_id'],
                    'apply_status'   => 1,
                    'effect_date'    => $val['indue_date'],
                    'opt_user_id'    => $super_data['user_id']
            );
            $this->regular_bll->insert_regular($regular_data);
            //写入operator_log表，标记为系统处理
            $log_data = array(
                    'user_id'      => $val['user_id'],
                    'user_name'    => $val['user_name'],
                    'opt_user_id'  => 1,//system
                    'role_type'    => Const_Flow::ROLE_SYSTEM,
                    'work_city_id' => $val['work_city_id'],
                    'flow_id'      => $flow_id,
                    'flow_opt'     => Const_Flow::PHASE_40,
                    'flow_stage'   => Const_Flow::FLOW_REGULAR_1,
                    'flow_type'    => Const_Flow::FLOW_TYPE_REGULAR,
                    'effect_date'  => $val['indue_date'],
            );
            $this->log_bll->save_log($log_data);
            //写入审批关系
            $this->rel_bll->insert($flow_id,$val['user_id'],$super_data['user_id'],Const_Flow::FLOW_REGULAR_2);
        }
        return true;
    }
    //所有需要续签
    private function _build_renew_users($data){
        $uids = array_keys($data);
        $jobinfo = $this->hr_bll->get_user_by_ids($uids);
        $sql = "SELECT * FROM user_renew WHERE user_id IN(".implode(',',$uids).") AND apply_status=1 ";
        $tmp_user_data = $this->get_db_rows_assoc($sql,$this->writedb,array());
        $has_user_data = array();
        if(!empty($tmp_user_data)){
            foreach($tmp_user_data as $val){
                $has_user_data[$val['user_id']] = $val;
            }
        }
        foreach($data as $val){
            if(!empty($has_user_data[$val['user_id']])){//事项中已存在的
                continue;
            }
            $super_data = $this->_get_user_super($val['user_id']);
            if(empty($super_data)){
                continue;
            }
            $in_flow = array(
                    'user_id'        => $val['user_id'],
                    'user_name'      => $val['user_name'],
                    'flow_type'      => Const_Flow::FLOW_TYPE_RENEW,
                    'flow_stage'     => Const_Flow::FLOW_RENEW_1,//当前阶段
                    'flow_opt'       => Const_Flow::PHASE_60,
                    'flow_role_list' => Const_Flow::ROLE_SUPERIOR,
                    'work_city_id'   => $val['work_city_id'],
                    'effect_date'    => $val['join_end'],
                    'now_status'     => 1,
            );
            $flow_id = $this->flow_bll->insert_flow($in_flow);
            $this->log("[JoinEndSEND]=====".$val['indue_date']."===".$val['user_id'].$val['user_name'].$val['user_code']."===".$flow_id);
            //信息表
            $renew_data = array(
                    'flow_id'        => $flow_id,
                    'user_id'        => $val['user_id'],
                    'user_name'      => $val['user_name'].'-'.$val['user_code'],
                    'department_name'=> $jobinfo[$val['user_id']]['department_name'],
                    'job_name'       => $jobinfo[$val['user_id']]['job_name'],
                    'job_id'         => $jobinfo[$val['user_id']]['job_id'],
                    'work_city_id'   => $val['work_city_id'],
                    'apply_status'   => 1,
                    'effect_date'    => $val['join_end'],
                    'opt_user_id'    => $super_data['user_id']
            );
            $this->renew_bll->insert_renew($renew_data);
            //写入operator_log表，标记为系统处理
            $log_data = array(
                    'user_id'      => $val['user_id'],
                    'user_name'    => $val['user_name'],
                    'opt_user_id'  => 1,//system
                    'role_type'    => Const_Flow::ROLE_SYSTEM,
                    'work_city_id' => $val['work_city_id'],
                    'flow_id'      => $flow_id,
                    'flow_opt'     => Const_Flow::PHASE_60,
                    'flow_stage'   => Const_Flow::FLOW_RENEW_1,
                    'flow_type'    => Const_Flow::FLOW_TYPE_RENEW,
                    'effect_date'  => $val['join_end'],
            );
            $this->log_bll->save_log($log_data);
            //写入审批关系
            $this->rel_bll->insert($flow_id,$val['user_id'],$super_data['user_id'],Const_Flow::FLOW_RENEW_2);
        }
        return true;
    }
    //得到主管
    private function _get_user_super($user_id){
        $super_data = $this->hr_bll->get_under_leader($user_id);
        if(empty($super_data)){
            $this->_error_info[]=$user_id." Not Found Super";
        }
        return $super_data;
    }
}